package cn.com.dhcc.app.pub.module.login.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.com.dhcc.app.core.annotation.WsdNoNeedLogin;
import cn.com.dhcc.app.core.base.user.LoginUser;
import cn.com.dhcc.app.core.exception.NiceException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.para.CorePara.StaticPara;
import cn.com.dhcc.app.core.tag.CommonStaticCode.SUCCESSFAIL;
import cn.com.dhcc.app.pub.core.AppPara.UAMS;
import cn.com.dhcc.app.pub.module.layout.controller.LayOutController;
import cn.com.dhcc.app.pub.module.login.service.LoginService;
import cn.com.dhcc.app.pub.module.login.vo.LoginCustomData;
import cn.com.dhcc.app.pub.module.usermgr.service.CmUserMgrService;
import cn.com.dhcc.app.pub.module.usermgr.vo.UserInfoVo;

/**
 * 包含非中央节点用户登录，注销，注册等功能，
 * 
 * @see {@link cn.com.dhcc.app.pub.core.interceptor.core.interceptor.AuthInterceptor} 权限验证
 * @日期：2012-12-27下午4:54:28
 * @作者：乔兵
 * @版权所有：东华软件
 * @版本：1.0
 */
@Controller
@RequestMapping("pub/")
public class LoginController extends cn.com.dhcc.app.core.base.BaseController {


	@Autowired
	private CmUserMgrService userMgrService;
	@Autowired
	private LoginService loginService;
	public static final String LOG_PAGE = "pub/login/login";
	public static final String LOGIN_REQUESTMAPPING = "login";
	public static final String LOGOUT_REQUESTMAPPING = "logout";

	/**
	 * 登录验证 针对没有单点登录的节点
	 * @param model
	 * @param httpSession
	 * @param userCode
	 * @param password
	 * @return
	 */
	@RequestMapping(LOGIN_REQUESTMAPPING)
	@WsdNoNeedLogin
	public String login(final Model model,HttpServletRequest request, HttpSession httpSession, String userName,
			String password) {
		//已经成功登录了，直接条跳转
		if (getCurrentUserInfo(httpSession) != null) {
			return "redirect:/"+LayOutController.INDEX_REQUESTMAPPING+".do";
		}
		if (StringUtils.hasText(userName) && StringUtils.hasText(password)) {
			LoginUser loginUser = null;
			try {
				//如果是超级管理员，通过配置文件取
				if(CmUserMgrService.getSuperAdmin()!=null && CmUserMgrService.getSuperAdmin().getUserName().equalsIgnoreCase(userName)){
					loginUser = CmUserMgrService.getSuperAdmin();
				}else{
					//如果用户来着外部统一用户接口，则需要用户自己去通过统一用户接口取用户数据
					if(UAMS.SSO_ENABLED){
						loginUser = null;//TODO 自定义,并统一转换成loginUser对象
				    //用户本系统自己管理的，从数据库取，并转为内部统一的LoginUser对象。
					}else if(UAMS.isSelfUser()){
						UserInfoVo	userInfoVoInner = userMgrService.getUserByName(userName);
						loginUser = userMgrService.toSsoUserFromInnerUserInfoVo(userInfoVoInner);
					}else{
						model.addAttribute("error", "用户来源类型配置错误！");
						return LOG_PAGE;
					}
				}
				if (loginUser != null) {
					//超级管理员和系统自己管理用户的情况，需要验证密码是否一致
					if(loginUser.isSuperAdmin()||UAMS.isSelfUser()){
						LoginCustomData customData = (LoginCustomData) loginUser.getCustomData();
					   if(!customData.getAdminPwd().equalsIgnoreCase(password)){
							model.addAttribute("error", "用户["+userName+"]密码错误！");
							return LOG_PAGE;
					   }
					}else{
						//如果是单点登陆的话，密码是加密的，用户密码验证有需要调用统一用户的接口去验证，这一块根据不同的项目自己实现
					}
					//加载菜单、权限资源
					loginService.loadUserResource(loginUser, httpSession);
					//放入seesion
					httpSession.setAttribute(StaticPara.USER_SESSION_KEY, loginUser);
				} else {
					model.addAttribute("error", "用户["+userName+"]不存在！");
					return LOG_PAGE;
				}
			}catch (NiceException e) {
				model.addAttribute("error", e.getMessage());
				safeLog("登陆管理", "用户登陆", SUCCESSFAIL.FAIL, e.getMessage());
				return LOG_PAGE;
			} catch (ServiceException e) {
				model.addAttribute("error", "用户信息检索失败");
				safeLog("登陆管理", "用户登陆", SUCCESSFAIL.FAIL, e.getMessage());
				return LOG_PAGE;
			}catch (Exception e) {
				model.addAttribute("error", "系统异常,请联系管理员！");
				safeLog("登陆管理", "用户登陆", SUCCESSFAIL.FAIL,"系统异常,请联系管理员！");
				return LOG_PAGE;
			}
			//登录成功
			return "redirect:/"+LayOutController.INDEX_REQUESTMAPPING+".do";
		} else {
			return LOG_PAGE;
		}
	}
	/**
	 * 退出
	 * @param httpSession
	 * @return
	 */
	@WsdNoNeedLogin
	@RequestMapping(LOGOUT_REQUESTMAPPING)
	public String logout(HttpSession httpSession) {
		safeLog("登陆管理", "用户注销", SUCCESSFAIL.SUCCESS,null);
		httpSession.invalidate();
		//单点退出
		if(UAMS.SSO_ENABLED){
			//注意这个地址需要和web.xml里面配置一样，如下：
			/*<!-- 客户端注销 -->
			<filter-mapping>
				<filter-name>SSO Authentication Filter</filter-name>
				<url-pattern>/loginOut</url-pattern>
			</filter-mapping>*/
			return "redirect:/loginOut";
		}else{//非单点退出
			return "redirect:/pub/login.do";
		}
	}
}
